package com.woniu.consumers;

import com.rabbitmq.client.Channel;
import com.woniu.service.TestDetailService;
import com.woniu.service.util.Sample;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class EndTestConsumer {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private TestDetailService testDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "endTestQueue")
    public void endTest(Message message, Map<String, Object> infoMap, Channel channel) throws Exception {
        String redisKey = (String) infoMap.get("redisKey");
        Long userCode = (Long) infoMap.get("userCode");
        String testId = (String) infoMap.get("testId");
        Date flagPostPone = (Date) redisTemplate.opsForValue().get(userCode + "-flag-" + testId + "-time");
        if (flagPostPone == null) {
            redisTemplate.delete(redisKey);
            testDetailService.closeTest(Long.parseLong(testId), userCode);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        long postPoneTime =(System.currentTimeMillis()-flagPostPone.getTime());
        if (postPoneTime > 0) {
            redisTemplate.expire(redisKey, postPoneTime, TimeUnit.MILLISECONDS);
            rabbitTemplate.convertAndSend("startTestExchange", "startTest", infoMap);
        } else {
            redisTemplate.delete(redisKey);
            testDetailService.closeTest(Long.parseLong(testId), userCode);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }
}
